<template>
  <div>
    <div
      v-if="searchStatus"
      class=""
      :class="!props.searchStatus ? '' : 'box-shadow pad10 mgb10'"
    >
      <el-form :model="queryParams" ref="queryRef" :inline="true" class="fnmb">
        <div class="flex jbetween">
          <div>
            <el-form-item :label="route.query.Label + '项编号'">
              <el-input
                v-model="queryParams.Code"
                placeholder="请输入"
                clearable
                style="width: 200px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item :label="route.query.Label + '项内容'">
              <el-input
                v-model="queryParams.Content"
                placeholder="请输入"
                clearable
                style="width: 200px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
          </div>
          <div class="flex jend acenter fnw">
            <el-button type="primary" icon="Search" @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </div>
        </div>
      </el-form>
    </div>
    <MyTable
      v-model:selectList="myselectList"
      v-model:page="page"
      v-model:searchStatus="searchStatus"
      :btnList="['delete', 'edit']"
      :tableList="tableList"
      :total="Total"
      :columns="columns"
      ref="tableRef"
      @delete="handleDelete"
      @getList="getList"
      @edit="handleEdit"
    >
      <template v-slot:tabTop>
        <el-button type="primary" icon="CirclePlusFilled" @click="handleAdd"
          >添加{{ route.query.Label }}项</el-button
        >
      </template>
    </MyTable>
    <MyDialog
      v-model:show="show"
      :title="title"
      :width="1000"
      @confirm="confirm"
    >
      <el-table
        :data="tableData"
        row-class-name="TableRowClass"
        header-row-class-name="TableHeaderClass"
      >
        <el-table-column
          prop="Code"
          :align="'center'"
          label="编号"
          width="160px"
        >
          <template v-slot="{ row }">
            <el-input v-model="row.Code" placeholder="请输入" clearable />
          </template>
        </el-table-column>
        <el-table-column :align="'center'" prop="Content" label="内容">
          <template v-slot="{ row }">
            <el-input v-model="row.Content" placeholder="请输入" clearable />
          </template>
        </el-table-column>
        <!-- <el-table-column
          :align="'center'"
          prop="Content"
          label="类型"
          width="160"
        >
          <template v-slot="{ row }">
            <Selector v-model="row.Type" category="全部用户" />
          </template>
        </el-table-column> -->
        <el-table-column
          prop="Code"
          :align="'center'"
          label="操作"
          width="160px"
          v-if="!formData.ID"
        >
          <template v-slot="{ row, $index }">
            <el-button type="text" @click="addTableData($index)"
              ><el-icon><Plus /></el-icon>添加</el-button
            >
            <el-button
              @click="deleteTableData($index)"
              v-if="$index != 0"
              type="text"
              style="color: red"
              ><el-icon><Delete /></el-icon>删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </MyDialog>
  </div>
</template>

<script setup name="TeachMaintainPalnItem">
import { ref, getCurrentInstance, onMounted, computed, onActivated } from "vue";

import {
  GetMaintainItemsList_Page,
  AddMaintainItem,
  EditMaintainItem,
  DelMaintainItem,
} from "@/api/teachDevice/maintain.js";
import { useRoute } from "vue-router";
const { proxy } = getCurrentInstance();
const emit = defineEmits(["update:selectList"]);
const route = useRoute();
const props = defineProps({
  searchStatus: {
    default: true,
  },
  selectList: {
    default: [],
  },
});

const tableList = ref([]);
const Total = ref(0);
const columns = ref([
  { label: "序号" },
  { label: "编号", prop: "Code", width: 160 },
  { label: "内容", prop: "Content" },
  // { label: "类型", prop: "TypeName", width: 120 },
  { label: "操作", width: 160 },
]);

if (!props.searchStatus) {
  columns.value.unshift({
    label: "多选框",
  });
}
proxy.$formatKey(columns.value);
const page = ref({
  PageIndex: 1,
  PageSize: 10,
});
const searchStatus = ref(true);
searchStatus.value = props.searchStatus;
const queryParams = ref({
  Code: "",
  Content: "",
  NoPage: "", //如果传"true"，则返回全部数据不分页
});
const queryRef = ref();
const show = ref(false);
const title = ref();
const tableRef = ref();
const rules = ref({
  Code: [{ required: true, message: "请输入", trigger: "blur" }],
  Content: [{ required: true, message: "请输入", trigger: "blur" }],
  Principal: [{ required: true, message: "请选择", trigger: "change" }],
});
const formData = ref({});
const tableData = ref([
  {
    Code: "",
    Content: "",
  },
]);
const origonList = ref([]);

onMounted(() => {
  origonList.value = props.selectList;
  getList();
});

const myselectList = computed({
  get: () => props.selectList,
  set: (n) => {
    origonList.value = origonList.value?.filter((item) => {
      let bool = n?.some((item2) => {
        return item2.ID == item.ID;
      });
      return !bool;
    });
    let list = [...origonList.value, ...n];
    emit("update:selectList", list);
  },
});

const Types = {
  1: "装备",
  2: "工具",
};
async function getList() {
  try {
    show.value = false;
    let query = {
      ...queryParams.value,
      ...page.value,
      Type: route.query.Type,
    };
    let res = await GetMaintainItemsList_Page(query);
    res.data.List?.forEach((item) => {
      item.TypeName = Types[route.query.Type];
    });
    tableList.value = res.data.List;
    Total.value = res.data.Total;
    validateRow();
  } catch (error) {
    console.log(error);
  }
}

function addTableData(index) {
  tableData.value.splice(index + 1, 0, { Code: "", Content: "" });
}
function deleteTableData(index) {
  tableData.value.splice(index, 1);
}

function validateRow() {
  tableList.value?.map((item) => {
    props.selectList?.map((item2) => {
      if (item.ID == item2.ID) {
        item.Sort = item2.Sort;
        tableRef.value.tabRef.toggleRowSelection(item, true);
      }
    });
  });
}

function handleEdit(row) {
  title.value = `修改${route.query.Label}项`;
  formData.value.ID = row.ID;
  tableData.value = [
    {
      ID: row.ID,
      Code: row.Code,
      Content: row.Content,
      Type: route.query.Type,
    },
  ];
  show.value = true;
}

async function confirm(val) {
  try {
    let bool = tableData.value?.every((item) => {
      return item.Code && item.Content;
    });
    if (!bool) return proxy.$modal.msgError("编号/内容，不能为空");
    tableData.value?.forEach((item) => (item.Type = route.query.Type));
    if (formData.value.ID) {
      await EditMaintainItem(JSON.stringify(tableData.value[0]));
      proxy.$modal.msgSuccess("修改成功");
    } else {
      await AddMaintainItem(JSON.stringify(tableData.value));
      proxy.$modal.msgSuccess("添加成功");
    }

    getList();
  } catch (error) {
    console.log(error);
  }
}

async function handleDelete(row) {
  try {
    await DelMaintainItem({ ID: row.ID });
    proxy.$modal.msgSuccess("删除成功");
    getList();
  } catch (error) {
    console.log(error);
  }
}
function handleAdd() {
  formData.value = {};
  tableData.value = [
    {
      Code: "",
      Content: "",
    },
  ];
  title.value = `添加${route.query.Label}项`;
  show.value = true;
}
function handleQuery() {
  page.value.PageIndex = 1;
  getList();
}
function resetQuery() {
  queryParams.value = {
    Code: "",
    Content: "",

    NoPage: "",
  };
  handleQuery();
}
</script>

<style lang="scss" scoped></style>
